package common

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var DB *gorm.DB

func ConnectToMysql() (*gorm.DB, error) {
	db := "mysql"
	dbName := "go_blog"
	dbUrl := "localhost:3306"
	dbUserName := "root"
	dbPassword := "123"
	charset := "utf8mb4"
	parseTime := "True"
	loc := "Local"
	openUrl := fmt.Sprintf("%s:%s@(%s)/%s?charset=%s&parseTime=%s&loc=%s", dbUserName, dbPassword, dbUrl, dbName, charset, parseTime, loc)
	_db, err := gorm.Open(db, openUrl)
	if err != nil {
		panic("数据库连接失败" + err.Error())
	} else {
		fmt.Println("数据库连接成功！")
		DB = _db
		return _db, err
	}
}

func GetDB() *gorm.DB {
	return DB
}
